Java IText
- Java PDF Generation with IText
- Getting Started with IText PDF API for Java
- Java IText: Document
- Java IText: Chunk
- Java IText: Phrase
- Java IText: Paragraph
- Java IText: Chapter + Section
- Java IText: Anchor (link)
- Java IText: List
- Java IText: Table
- Java IText: Image
- Java IText: Superscript + Subscript
- Java IText: Underline + Strikethrough
- Java IText: Font
- Java IText: Modifying Existing PDF Documents
Getting Started with IText PDF API for Java
Jakob Jenkov |
To use IText PDF API for Java you must first download the IText JAR file from the IText website, and include it on your application class path.
Here is a simple code example that generates a very simple PDF document using IText:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
/**
*/
public class HelloWorldExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close(); // no need to close PDFwriter?
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Here is what happens in the code example:
- First a
Documentinstance is created. ThisDocumentinstance represents the PDF document. To add content to the PDF document, you call methods on theDocumentinstance.
-
Second, a
PDFWriteris created, passing theDocumentinstance and anOutputStreamto its constructor. TheDocumentinstance is the document we are currently adding content to. TheOutputStreamis where the generated PDF document is written to. In this example the PDF document is written to a file, using aFileOutputStream.
-
Third, the document is opened by calling
document.open(). Now you can add content to theDocumentinstance.
-
Fourth, content (a
Paragraphinstance) is added to theDocumentinstance.
-
Fifth, the
Documentinstance is closed, by callingdocument.close(). It is important to close the document, to flush all content in the document to thePDFWriter.
That's it.
Next: Java IText: Document
| Tweet | |
Jakob Jenkov | |









